package net.qiyuesuo.dao.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import net.qiyuesuo.utils.file.PropertiesUtils;

/**
 * 使用单例模式 管理DataSource
 *
 */
public class DataSourceConfig {
	
		private HikariDataSource da = null;
		
	 	private DataSourceConfig() {
	 		String database = PropertiesUtils.getDataBaseProperty("database");
	 		String url = null;
	 		String username = null;
	 		String password = null;
	 		switch (database) {
			case "mysql":
				url = PropertiesUtils.getDataBaseProperty("mysql.url");
				username = PropertiesUtils.getDataBaseProperty("mysql.username");
				password = PropertiesUtils.getDataBaseProperty("mysql.password");
				break;
			case "sqlserver":
				url = PropertiesUtils.getDataBaseProperty("sqlserver.url");
				username = PropertiesUtils.getDataBaseProperty("sqlserver.username");
				password = PropertiesUtils.getDataBaseProperty("sqlserver.password");
				break;	
			case "oracle":
				url = PropertiesUtils.getDataBaseProperty("oracle.url");
				username = PropertiesUtils.getDataBaseProperty("oracle.username");
				password = PropertiesUtils.getDataBaseProperty("oracle.password");
				break;	
			default:
				break;
			}
	 		//配置 HikariCP
			HikariConfig config = new HikariConfig();
			config.setJdbcUrl(url);
			config.setUsername(username);
			config.setPassword(password);
			
			config.addDataSourceProperty("cachePrepStmts", "true"); //是否自定义配置，为true时下面两个参数才生效
			config.addDataSourceProperty("prepStmtCacheSize", "250"); //连接池大小默认25，官方推荐250-500
			config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); //单条语句最大长度默认256，官方推荐2048
			config.addDataSourceProperty("useServerPrepStmts", "true"); //新版本MySQL支持服务器端准备，开启能够得到显著性能提升
			//创建数据库连接池
			this.da = new HikariDataSource(config);	 		
	 	}
	 	
	 	public HikariDataSource getDataSource() {
	 		return da;
	 	}
	 	
	 	
	 	public static class Singleton{
	 		private static DataSourceConfig instance = new DataSourceConfig();
	 	}
	 	
	 	public static DataSourceConfig instance() {
	 		return Singleton.instance;
	 	}
	 	
}
